import { useState } from "react"
import { message } from "antd"
import {
  getPostList,
  deletePost,
  updatePost,
  createPost
} from "api/system/post"

import { IModalProps } from "app/interfaces/system"

interface IForm {
  postId: string
  postName: string
  postCode: string
  postSort: number
  status: string
  remark: string
}
export interface IEditProps extends IModalProps<IForm> {
  submitForm: (params: IForm) => void
}

export function usePost() {
  const initForm = {
    postId: "",
    postName: "",
    postCode: "",
    postSort: 0,
    status: "",
    remark: ""
  }

  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(false)
  const [dataSource, setDataSource] = useState([])
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  const [queryParams, setQueryParams] = useState({
    postName: "",
    status: "",
    pageNum: 1,
    pageSize: 10
  })

  const [form, setForm] = useState<IForm>(initForm)
  const [modalConfig, setModalConfig] = useState({
    title: "",
    visible: false
  })

  const getList = async () => {
    try {
      setLoading(true)
      const { code, data } = await getPostList(queryParams)
      if (code === 200) {
        setDataSource(data.rows)
        setTotal(data.total)
      }
      setLoading(false)
    } catch (e) {
      console.log(e)
      setLoading(false)
    }
  }

  const submitForm = async (params) => {
    try {
      const service = params.postId ? updatePost : createPost
      console.log(params)
      const { code } = await service(params)
      if (code === 200) {
        setModalConfig({ ...modalConfig, visible: false })
        message.success("操作成功")
        await getList()
      }
    } catch (e) {
      console.log(e)
    }
  }

  const handleDelete = async (ids) => {
    try {
      const { code } = await deletePost({ ids })
      if (code === 200) {
        message.success("删除成功")
        await getList()
      }
    } catch (e) {
      console.log(e)
    }
  }

  return {
    getList,
    handleDelete,
    submitForm,
    loading,
    setLoading,
    total,
    dataSource,
    setDataSource,
    selectedRowKeys,
    setSelectedRowKeys,
    queryParams,
    setQueryParams,
    initForm,
    form,
    setForm,
    modalConfig,
    setModalConfig
  }
}
